package com.ruoyi.merchant.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.cg.pojo.Community;
import com.ruoyi.common.core.cg.pojo.Leader;
import com.ruoyi.common.core.cg.pojo.QQMapCommunity;
import com.ruoyi.common.core.cg.result.Result;
import com.ruoyi.merchant.mapper.CommunityMapper;
import com.ruoyi.merchant.service.CommunityService;
import com.ruoyi.merchant.utils.ali.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author ？？？
* @description 针对表【community】的数据库操作Service实现
* @createDate 2025-03-13 08:38:20
*/
@Service
public class CommunityServiceImpl implements CommunityService{
    private final String KEY = "RJ6BZ-SHDKW-OCDR3-YRCRE-CL2VQ-Z4BST";
    private final String KEYWORD = "社区";
    @Autowired
    private CommunityMapper mapper;
    /**
     * 查询周边社区
     * @param latitude 纬度
     * @param longitude 精度
     * @return
     */
    @Override
    public List<Community> findNearCommunity(BigDecimal latitude, BigDecimal longitude) throws Exception{
        String urlStr = "https://apis.map.qq.com/ws/place/v1/search?" +
                "key="+KEY+
                "&keyword="+KEYWORD+
                "&boundary=nearby("+latitude+","+longitude+",1000)&page_size=10&page_index=1";
        URL url = new URL(urlStr);
        // 打开链接
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        // 获取响应码
        Integer responseCode = httpURLConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 解析 JSON 响应
            String responseJson = response.toString();
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> map = objectMapper.readValue(responseJson, Map.class);
            List<Object> objectList = (List<Object>) map.get("data");
            List<QQMapCommunity> qqMapCommunityList = new ArrayList<>();
            for (Object obj:objectList){
                Map<String,Object> objectMap = (Map<String, Object>) obj;
                QQMapCommunity qqMapCommunity = new QQMapCommunity();
                qqMapCommunity.setId((String) objectMap.get("id"));
                BigDecimal bigDecimalFromConstructor = new BigDecimal((Double) objectMap.get("_distance"));
                qqMapCommunity.set_distance(bigDecimalFromConstructor);
                qqMapCommunity.setAddress((String) objectMap.get("address"));
                qqMapCommunity.setTitle((String) objectMap.get("title"));
                qqMapCommunity.setLocation((Map<String, String>) objectMap.get("location"));
                qqMapCommunityList.add(qqMapCommunity);
            }
            List<Community> communityList = new ArrayList<>();
            for (QQMapCommunity qqMapCommunity:qqMapCommunityList){
                Community community = new Community();
                community.setTitle(qqMapCommunity.getTitle());
                community.setQqMapId(qqMapCommunity.getId());
                community.setAddress(qqMapCommunity.getAddress());
                community.set_distance(qqMapCommunity.get_distance());
                community.setLat(String.valueOf(qqMapCommunity.getLocation().get("lat")));
                community.setLng(String.valueOf(qqMapCommunity.getLocation().get("lng")));
                Community communityByQQmapId = mapper.findCommunityByQQmapId(qqMapCommunity.getId());
                if (null != communityByQQmapId){
                    Integer member = mapper.findMemberById(communityByQQmapId.getId());
                    community.setMember(member);
                    Leader leader = mapper.findLeaderById(communityByQQmapId.getId());
                    community.setLeader(leader);
                }
                communityList.add(community);
            }
            return communityList;
        }
        return null;
    }
}




